import { Editor } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css';
import { Button } from 'antd';
import { useEffect, useState } from 'react';

function MyEditor(props) {
  const {
    editorStyle = {},
    closeEditor = () => {},
    editorSubmit = () => {},
  } = props;
  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [editorValue, setEditorValue] = useState('');
  const toolbarConfig = {
    toolbarKeys: ['bold', 'color', 'fontSize'],
  };
  const editorConfig = {
    placeholder: '请输入内容...',
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor === null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  function insertText() {
    if (editor === null) return;
    editor.insertText(' hello ');
  }

  function printHtml() {
    if (editor === null) return;
    console.log(editor.getHtml());
  }

  return (
    <>
      <div
        style={{
          position: 'absolute',
          border: '1px solid #ccc',
          zIndex: 99999,
          width: '300px',
          ...editorStyle,
          padding: '10px',
          background: '#FFF',
        }}
      >
        <Editor
          defaultConfig={editorConfig}
          value={editorValue}
          onCreated={setEditor}
          onChange={(editor) => setEditorValue(editor.getHtml())}
          mode="default"
          style={{ height: '100px' }}
        />
        <div
          style={{
            background: '#FFF',
            display: 'flex',
            justifyContent: 'flex-end',
          }}
        >
          <Button onClick={closeEditor} style={{ marginRight: '10px' }}>
            取消
          </Button>
          <Button onClick={editorSubmit.bind(this, editorValue)}>确定</Button>
        </div>
      </div>
    </>
  );
}

export default MyEditor;
